package com.emex.app.stuff.gui;

import com.emex.app.shared.data.Profit;
import com.emex.app.shared.data.ProfitType;
import com.emex.app.shared.data.enums.PayMethod;
import com.emex.app.stuff.gui.model.ProfitTableModel;
import com.emex.app.stuff.gui.model.ProfitTypeComboBoxModel;
import com.emex.app.stuff.provider.ProfitDataProvider;
import com.emex.app.stuff.utils.StringUtilities;
import com.emex.app.stuff.utils.UIUtils;
import java.util.Date;
import java.util.Objects;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author Sergey Karavaev
 */
public class ProfitDialog extends javax.swing.JDialog {

    private Profit profit;
    private Date date;
    private ProfitTableModel profitTableModel;

    /**
     * Creates new form ProfitDialog
     */
    public ProfitDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        ProfitTypeComboBoxModel cbModel = new ProfitTypeComboBoxModel();
        profitTypeComboBox.setModel(cbModel);
        payMethodComboBox.setModel(new DefaultComboBoxModel(PayMethod.values()));
    }

    public ProfitTableModel getProfitTableModel() {
        return profitTableModel;
    }

    public void setProfitTableModel(ProfitTableModel profitTableModel) {
        this.profitTableModel = profitTableModel;
    }
    
    

    public Profit getProfit() {
        return profit;
    }

    public void setProfit(Profit profit) {
        this.profit = profit;
        if (this.profit != null) {
            ProfitType ct = ProfitDataProvider.getInstance().selectProfitTypeByPrimaryKey(profit.getProfitType());
            if (null != ct && profitTypeComboBox.getItemCount() > 0) {
                for (int i = 0; i < profitTypeComboBox.getItemCount(); ++i) {
                    ProfitType p = (ProfitType) profitTypeComboBox.getItemAt(i);
                    if (Objects.equals(ct.getId(), p.getId())) {
                        profitTypeComboBox.setSelectedIndex(i);
                        break;
                    }
                }
            }
            summaField.setText(profit.getSumma().toString());
            payMethodComboBox.setSelectedItem(PayMethod.valueOf(profit.getPayMethod()));
            commentTextArea.setText(profit.getComment());
        }
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        profitTypeComboBox = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        summaField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        payMethodComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        commentTextArea = new javax.swing.JTextArea();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.jLabel1.text")); // NOI18N

        profitTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Загрузка..." }));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.jLabel2.text")); // NOI18N

        summaField.setText(org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.summaField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.jLabel3.text")); // NOI18N

        payMethodComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Загрузка..." }));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.jLabel4.text")); // NOI18N

        commentTextArea.setColumns(20);
        commentTextArea.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        commentTextArea.setRows(5);
        jScrollPane1.setViewportView(commentTextArea);

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.saveButton.text")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(ProfitDialog.class, "ProfitDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(summaField)
                            .addComponent(payMethodComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                            .addComponent(profitTypeComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(profitTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(summaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(payMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        boolean isCreate = false;

        if (null == profit) {
            profit = new Profit();
            isCreate = true;
        }

        if (null == summaField.getText() || summaField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Укажите сумму");
            return;
        }

        if (null == profitTypeComboBox.getSelectedItem()) {
            UIUtils.showErrorMessage("Выберите статью расхода");
            return;
        }
        if (null == payMethodComboBox.getSelectedItem()) {
            UIUtils.showErrorMessage("Выберите тип оплаты");
            return;
        }

        ProfitType ct = (ProfitType) profitTypeComboBox.getSelectedItem();
        if (null != ct) {
            profit.setProfitType(ct.getId());
        }

        PayMethod payMethod = (PayMethod) payMethodComboBox.getItemAt(payMethodComboBox.getSelectedIndex());
        profit.setPayMethod(payMethod.ordinal());
        profit.setSumma(Double.valueOf(summaField.getText().replaceAll(",", ".")));
        profit.setComment(StringUtilities.fromUpperCase(commentTextArea.getText()));

        if (isCreate) {
            profit.setDate(date);
            profit = ProfitDataProvider.getInstance().insertProfit(profit);
            if (null != profitTableModel) {
                profitTableModel.dataAdded(profit);
            }
        } else {
            ProfitDataProvider.getInstance().updateProfitByPrimaryKey(profit);
            if (null != profitTableModel) {
                profitTableModel.dataUpdated();
            }
        }
        this.setVisible(false);
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextArea commentTextArea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox payMethodComboBox;
    private javax.swing.JComboBox profitTypeComboBox;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField summaField;
    // End of variables declaration//GEN-END:variables
}
